package artid.com.arttogo.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import artid.com.arttogo.R;
import artid.com.arttogo.adapter.AuctionInfo_Adapter;
import artid.com.arttogo.bean.AuctionInfoParser;
import artid.com.arttogo.bean.SpecialListParser;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.network.AppUtil;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.utils.MyBitmapImageViewTarget;
import artid.com.arttogo.utils.NetUtils;
import artid.com.arttogo.utils.ToastUtil;
import artid.com.arttogo.utils.VeDate;
import artid.com.arttogo.view.CircleImageView;
import artid.com.arttogo.view.DynamicHeightImageView;
import artid.com.arttogo.view.MyListView;
import artid.com.arttogo.view.ZoomScollView;
import artid.com.arttogo.view.pulllist.PullToRefreshLayout;
import artid.com.arttogo.view.pulllist.PullableScrollView;
import static android.R.attr.resource;
import static android.R.attr.width;
import static artid.com.arttogo.app.ArtToGoApp.getActivity;


/**
 * 项目名称：ArtworkArt
 * 类名称：AuctionInfo_Activity
 * 类描述：拍卖会详情
 * 创建人：耿卫斌
 * 创建时间：2017-3-2 下午4:05:12
 */
public class AuctionInfo_Activity extends BaseActivity implements OnClickListener {
    private PullToRefreshLayout mPullToRefreshLayout;
    private ZoomScollView scrollView;
    private ImageView backBtn,titleCollectionBtn, moreBtn;
    DynamicHeightImageView lotImg;
    private RelativeLayout zoomRL,auctionInfo_RL,auctionRL;
    private LinearLayout artistLL, commentLL,allroot;
    private TextView title, previewTime, previewAddress, auctionTime, auctionAddress, company, commentTv,
            artistNumTv, artistList, specialNum;
    private ImageView company_icon;
    private MyListView mListView;
    private AuctionInfo_Adapter mAdapter;
    private boolean isRefreshed = false;// 是否刷新
    private int page = 1;
    private int artistNum;//艺术家数量
    private String auctionID;//拍卖会ID
    private List<SpecialListParser> list = new ArrayList<SpecialListParser>();
    private List<SpecialListParser> more_list = new ArrayList<SpecialListParser>();
    private AuctionInfoParser mAuctionInfoParser;
    private String SpecialListData;//请求专场列表默认请求全部
    private LinearLayout mHeadView;
    private TextView titleContent;
    private int width, height;
    private String imgwide;// 请求的图片宽度
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auctioninfo);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //刷新拍卖会信息主要是刷新评论条数
        getAuctionInfoData();
    }

    public int getScrollY() {
        int top = mHeadView.getTop();
        return -top;
    }

    private void initView() {
        mContext = AuctionInfo_Activity.this;
        imgwide = (Integer.parseInt(NetUtils.getDisplayMetrics((Activity) mContext).get(NetUtils.DM_WIDTH)) / 1) + "";
        titleContent = (TextView) findViewById(R.id.tittle_text);
        zoomRL = (RelativeLayout) findViewById(R.id.AuctionInfo_zoomRL);
        scrollView = (ZoomScollView) findViewById(R.id.AuctionInfo_PullableScrollView);
        scrollView.setIsDrop(true);//是否开启下拉刷新
        scrollView.ZoomHeight=true;
        mHeadView = (LinearLayout) findViewById(R.id.rel_h);
        backBtn = (ImageView) findViewById(R.id.back_btn);
        backBtn.setOnClickListener(this);
        titleCollectionBtn = (ImageView) findViewById(R.id.AuctionInfo_title_collectionBtn);
        titleCollectionBtn.setVisibility(View.GONE);
        titleCollectionBtn.setOnClickListener(this);
        moreBtn = (ImageView) findViewById(R.id.tittle_search);
        moreBtn.setImageResource(R.drawable.jg_xq_share);
        moreBtn.setVisibility(View.VISIBLE);
        moreBtn.setOnClickListener(this);
        IntentFilter filter = new IntentFilter("com.AuctionInfo_Activity.receiver");
        registerReceiver(broadcastReceiver, filter);
        auctionID = getIntent().getStringExtra("auctionID");
        SpecialListData = getIntent().getIntExtra("SpecialListData", 0) + "";
        mPullToRefreshLayout = (PullToRefreshLayout) findViewById(R.id.AuctionInfo_refresh_layout);
        lotImg = (DynamicHeightImageView) findViewById(R.id.AuctionInfo_lotImg);
        lotImg.isRightAngle=true;
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        width = dm.widthPixels;
        height = dm.heightPixels;
        auctionRL = (RelativeLayout) findViewById(R.id.AuctionInfo_auctionRL);
        auctionRL.setOnClickListener(this);
        title = (TextView) findViewById(R.id.AuctionInfo_title);
        previewTime = (TextView) findViewById(R.id.AuctionInfo_previewTime);
        previewAddress = (TextView) findViewById(R.id.AuctionInfo_previewAddress);
        auctionTime = (TextView) findViewById(R.id.AuctionInfo_auctionTime);
        auctionAddress = (TextView) findViewById(R.id.AuctionInfo_auctionAddress);
        company_icon = (ImageView) findViewById(R.id.AuctionInfo_company_icon);
        company_icon.setOnClickListener(this);
        company = (TextView) findViewById(R.id.AuctionInfo_company);
        artistLL = (LinearLayout) findViewById(R.id.AuctionInfo_artistLL);
        artistLL.setOnClickListener(this);
        artistNumTv = (TextView) findViewById(R.id.AuctionInfo_artistNum);
        artistList = (TextView) findViewById(R.id.AuctionInfo_artistList);
        specialNum = (TextView) findViewById(R.id.AuctionInfo_specialNum);
        mListView = (MyListView) findViewById(R.id.AuctionInfo_ListView);
        mListView.setOnItemClickListener(onItemClick);
        commentLL = (LinearLayout) findViewById(R.id.AuctionInfo_commentLL);
        commentLL.setOnClickListener(this);
        commentTv = (TextView) findViewById(R.id.AuctionInfo_commentTv);
        mPullToRefreshLayout.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                // TODO Auto-generated method stub
                // 下拉刷新
                page = 1;
                isRefreshed = true;
                getAuctionInfoData();
                getSpecialListData();
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                // TODO Auto-generated method stub
                // 上拉加载
                page++;
                getSpecialListData();
            }
        });
        getAuctionInfoData();
        getSpecialListData();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent intent;
        switch (v.getId()) {
            case R.id.back_btn:
                //返回
                finish();
                break;
            case R.id.AuctionInfo_title_collectionBtn:
                //收藏

                break;
            case R.id.tittle_search:
                //分享
                if (mAuctionInfoParser != null) {
                    AppUtil.shareAuction(mContext, "2", mAuctionInfoParser.getTitle(), mAuctionInfoParser.getMemo(), mAuctionInfoParser.getImgurl(),
                            mAuctionInfoParser.getShareurl() + "&type=1", mAuctionInfoParser.getId(), false);
                }
                break;
            case R.id.AuctionInfo_auctionRL:
                //查看拍卖会详情
                intent = new Intent(mContext, AuctionInformation_Activity.class);
                intent.putExtra("auctionID", auctionID);
                startActivity(intent);
                break;
            case R.id.AuctionInfo_artistLL:
                //查看艺术家详情
                if (artistNum != 0) {
                    intent = new Intent(mContext, AuctionArtist_Activity.class);
                    intent.putExtra("auctionID", auctionID);
                    startActivity(intent);
                } else {
                    ToastUtil.toast(mContext, "艺术家暂无");
                }
                break;
            case R.id.AuctionInfo_company_icon:
                //机构头像
                if (mAuctionInfoParser != null) {
                    intent = new Intent(mContext, AucOrgDetActivity.class);
                    intent.putExtra("id", mAuctionInfoParser.getJid());
                    startActivity(intent);
                }
                break;
            case R.id.AuctionInfo_commentLL:
                //评论
                intent = new Intent(mContext, AuctionComment_Activity.class);
                intent.putExtra("ID", auctionID);
                intent.putExtra("Type", "2");
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /**
     * 所有专场列表Item点击事件
     */
    OnItemClickListener onItemClick = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                long arg3) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(mContext, AuctionSpecialInfo_Activity.class);
            intent.putExtra("SpecialID", more_list.get(position).getId());
            startActivity(intent);
        }
    };

    /**
     * 获取拍卖详情数据
     */private void  getAuctionInfoData() {
        VolleyBasic.getInstance(this).post(Cache.auctionInfo,
                VolleyMap.getInstance().auctionInfo(auctionID,imgwide),
                AuctionInfoParser.class, new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        final AuctionInfoParser bean = (AuctionInfoParser) vd.getData();
                        mAuctionInfoParser = bean;
                        lotImg.setHeight(bean.getHeight());
                        try {
                            Glide.with(mContext).load(bean.getImgurl()).asBitmap().centerCrop().into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                    int w = resource.getWidth();
                                    int h = resource.getHeight();
                                    if(bean.getHeight()==0){
                                        lotImg.setHeight(h);
                                        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) company_icon.getLayoutParams();
                                        lp.setMargins(0,(h-150),0,0);
                                        company_icon.setLayoutParams(lp);
                                    }else{
                                        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) company_icon.getLayoutParams();
                                        lp.setMargins(0,(bean.getHeight()-150),0,0);
                                        company_icon.setLayoutParams(lp);
                                    }
                                    lotImg.setImageBitmap(resource);
                                }
                            });
                        } catch (Exception e) {
                            // TODO: handle exception
                        }
                        /*//下拉放大
                        ViewGroup.LayoutParams lp = zoomRL.getLayoutParams();
                        int w = zoomRL.getWidth();
                        int h = zoomRL.getHeight();
                        lp.width = width;
                        lp.height = h * width / w;
                        zoomRL.setLayoutParams(lp);
                        scrollView.setZoomView(zoomRL, true);
                        */
                        //titleContent.setText(bean.getTitle());//标题
                        title.setText(bean.getTitle());
                        previewTime.setText(bean.getPreview_start_time() + "-" + bean.getPreview_end_time());
                        previewAddress.setText(bean.getPreview_address());
                        auctionTime.setText(bean.getAuction_start_time() + "-" + bean.getAuction_end_time());
                        auctionAddress.setText(bean.getAuction_address());
                        Glide.with(mContext).load(bean.getLogo() + "_150x150.png"
                        ).asBitmap().centerCrop().placeholder(R.drawable.ic_menu_rotate).error(R.drawable.ic_menu_rotate)
                                .into(new MyBitmapImageViewTarget(company_icon));
                        company.setText(bean.getSeller_name());
                        artistNum = bean.getArtistNum();
                        artistNumTv.setText("艺术家（" + artistNum + "）");
                        if (!TextUtils.isEmpty(bean.getArtists()) && !"null".equals(bean.getArtists())) {
                            artistList.setText(bean.getArtists());
                        }
                        commentTv.setText("说说这场拍卖会（" + bean.getComNum() + "）");
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub
                    }
                });
    }

    /**
     * 获取专场列表数据
     * 拍卖会id	id
     * 页码	page
     * 条数	pagesize
     * 类型	type	默认是1，2表示往期拍卖会 /3 表示首页进入的热门专场/0全部
     */
    private void getSpecialListData() {
        VolleyBasic.getInstance(this).post(Cache.specialList,
                VolleyMap.getInstance().specialList(page, 10, auctionID, SpecialListData),
                SpecialListParser.class, new VolleyCallback() {
                    @SuppressWarnings({"unchecked", "static-access"})
                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        mPullToRefreshLayout.loadmoreFinish(mPullToRefreshLayout.SUCCEED);
                        try {
                            if (page == 1) {
                                //当请求第二页的时候num不会返回值
                                JSONObject obj = new JSONObject(vd.getJson());
                                String num = obj.optString("num");
                                specialNum.setText("所有专场（" + num + "）");
                            }
                            list = (List<SpecialListParser>) vd.getList();
                            if (isRefreshed == true) {
                                more_list.clear();
                                isRefreshed = false;
                            }
                            if (!list.isEmpty()) {
                                more_list.addAll(list);
                            }
                            if (mAdapter == null) {
                                mAdapter = new AuctionInfo_Adapter(mContext, more_list);
                                mListView.setAdapter(mAdapter);
                            }
                            mAdapter.notifyDataSetChanged();
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub
                        mPullToRefreshLayout.loadmoreFinish(mPullToRefreshLayout.FAIL);
                    }
                });
    }


    /**
     * 广播接收器
     */
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            if (intent.getBooleanExtra("addRemind", false)) {
                //判断是否为添加提醒的广播通知
                String specialId = intent.getStringExtra("specialId");
                if (more_list != null && more_list.size() != 0) {
                    //修改状态
                    for (int i = 0; i < more_list.size(); i++) {
                        if (more_list.get(i).getId().equals(specialId)) {
                            more_list.get(i).setIs_remind(2);
                            mAdapter.notifyData(more_list);
                        }
                    }
                }
            } else if (intent.getBooleanExtra("Collect", false)) {
                //是否为收藏
                if (intent.getBooleanExtra("isCollect", true)) {
                    //设置为已收藏
                } else {
                    //设置为未收藏
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        // 关闭广播
        unregisterReceiver(broadcastReceiver);
    }
}
